<template>
  <div>
    <el-form :inline="true">
      <el-form-item>
        <el-input v-model="searchForm.mechanismName"
                  placeholder="请输入机构名称..."
                  clearable>
        </el-input>
      </el-form-item>

      <el-form-item>
        <el-button @click="getMechanismList">搜索</el-button>
      </el-form-item>

      <el-form-item>
        <el-button type="primary"
                   @click="addHandle()">新增</el-button>
      </el-form-item>
      <el-form-item>
        <el-popconfirm title="确定批量删除吗？"
                       @confirm="delHandle(null)">
          <el-button type="danger"
                     slot="reference"
                     :disabled="delBtlStatu">批量删除</el-button>
        </el-popconfirm>
      </el-form-item>
    </el-form>
    <el-table ref="multipleTable"
              :data="tableData"
              v-loading="loading"
              row-key="id"
              tooltip-effect="dark"
              style="width: 100%"
              border
              stripe
              @selection-change="handleSelectionChange">
      <template slot="empty">
        <el-empty :image-size="400"></el-empty>
      </template>
      <el-table-column type="selection"
                       width="55"
                       label="序号"></el-table-column>
      <el-table-column type="index"
                       width="50"> </el-table-column>
      <el-table-column prop="mechanismNumber"
                       label="机构编号"
                       show-overflow-tooltip>
      </el-table-column>
      <el-table-column prop="mechanismName"
                       label="机构名称"
                       show-overflow-tooltip>
      </el-table-column>
      <el-table-column prop="created"
                       label="创建日期"
                       show-overflow-tooltip>
      </el-table-column>
      <el-table-column prop="legalRepresentative"
                       label="法定代表人"
                       show-overflow-tooltip>
      </el-table-column>

      <el-table-column prop="icon"
                       label="操作">
        <template slot-scope="scope">
          <el-button type="success"
                     plain
                     size="mini"
                     style="margin-right: -2px"
                     @click="infoHandler(scope.row.id)">详情
          </el-button>
          <el-button type="primary"
                     plain
                     size="mini"
                     @click="editHandle(scope.row.id)"
                     style="margin-right: 6px">修改</el-button>
          <template>
            <el-popconfirm title="确定删除吗？"
                           @confirm="delHandle(scope.row.id)">
              <el-button size="mini"
                         type="danger"
                         plain
                         slot="reference">删除</el-button>
            </el-popconfirm>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination @size-change="handleSizeChange"
                   @current-change="handleCurrentChange"
                   layout="total, sizes, prev, pager, next, jumper"
                   :page-sizes="[10, 20, 50, 100]"
                   :current-page="current"
                   :page-size="size"
                   :total="total">
    </el-pagination>
    <!-- 1 -->
    <el-dialog custom-class="container-box"
               title=""
               :close-on-click-modal="false"
               append-to-body
               :visible.sync="MechanismInfoVisible"
               width="80%"
               :before-close="handleCloseForDepartment">
      <div>
        <el-form :model="editForm"
                 ref="editForm"
                 :rules="editFormRules"
                 label-width="100px">
          <br />
          <el-tag>基本信息 ⮛⮛⮛⮛</el-tag>
          <br />
          <el-form-item label="机构角色"
                        prop="mechanismType">
            <el-checkbox-group v-model="editForm.mechanismType">
              <el-checkbox label="银行"
                           name="mechanismType"></el-checkbox>
              <el-checkbox label="保理公司"
                           name="mechanismType"></el-checkbox>
              <el-checkbox label="担保机构"
                           name="mechanismType"></el-checkbox>
              <el-checkbox label="证券公司"
                           name="mechanismType"></el-checkbox>
              <el-checkbox label="信托公司"
                           name="mechanismType"></el-checkbox>
              <el-checkbox label="保险公司"
                           name="mechanismType"></el-checkbox>
              <el-checkbox label="评估机构"
                           name="mechanismType"></el-checkbox>
              <el-checkbox label="基金管理公司"
                           name="mechanismType"></el-checkbox>
              <el-checkbox label="金融租赁公司"
                           name="mechanismType"></el-checkbox>
              <el-checkbox label="融资租赁公司"
                           name="mechanismType"></el-checkbox>
              <el-checkbox label="会计事务所"
                           name="mechanismType"></el-checkbox>
              <el-checkbox label="律师事务所"
                           name="mechanismType"></el-checkbox>
              <el-checkbox label="其他"
                           name="mechanismType"></el-checkbox>
            </el-checkbox-group>
          </el-form-item>

          <el-form-item label="机构编号"
                        prop="mechanismNumber"
                        label-width="100px">
            <el-input :disabled="true"
                      v-model="editForm.mechanismNumber"
                      autocomplete="off"></el-input>
          </el-form-item>

          <el-form-item label="机构名称"
                        prop="mechanismName"
                        label-width="100px">
            <el-input v-model="editForm.mechanismName"
                      autocomplete="off"></el-input>
          </el-form-item>

          <el-form-item label="机构状态"
                        prop="mechanismStatu"
                        label-width="100px">
            <el-input v-model="editForm.mechanismStatu"
                      :disabled="true"></el-input>
          </el-form-item>

          <el-form-item label="证件有效期"
                        prop="validity"
                        ref="validity">
            <el-date-picker type="date"
                            placeholder="证件有效期"
                            v-model="editForm.validity"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            :picker-options="pickerOptions"
                            style="width: 87%"></el-date-picker>
          </el-form-item>

          <el-form-item label="法定代表人"
                        prop="legalRepresentative"
                        label-width="100px"
                        style="margin-left: -2.5%">
            <el-input v-model="editForm.legalRepresentative"
                      autocomplete="off"></el-input>
          </el-form-item>

          <el-form-item label="主办部门"
                        prop="hostDepartment"
                        label-width="100px">
            <el-input v-model="editForm.hostDepartment"
                      autocomplete="off"
                      :disabled="true"></el-input>
          </el-form-item>

          <br />
          <el-form-item label="拜访次数"
                        prop="visit"
                        label-width="100px">
            <el-input v-model="editForm.visit"
                      autocomplete="off"
                      :disabled="true"></el-input>
          </el-form-item>

          <el-form-item label="来访次数"
                        prop="visitedTime"
                        label-width="100px">
            <el-input v-model="editForm.visitedTime"
                      autocomplete="off"
                      :disabled="true"></el-input>
          </el-form-item>

          <el-form-item label="创建日期"
                        prop="created"
                        label-width="100px">
            <el-input v-model="editForm.created"
                      autocomplete="off"
                      :disabled="true"></el-input>
          </el-form-item>
          <br />

          <el-form-item label="统一社会信用代码证"
                        prop="usccl"
                        label-width="150px">
            <el-input v-model="editForm.usccl"
                      style="width: 375%"></el-input>
          </el-form-item>
          <br />
          <el-form-item label="注册地址"
                        prop="registereAddress"
                        label-width="150px">
            <el-input v-model="editForm.registereAddress"
                      autocomplete="off"
                      style="width: 375%"></el-input>
          </el-form-item>
          <br />
          <el-form-item label="营业地址"
                        prop="businessAddress"
                        label-width="150px">
            <el-input v-model="editForm.businessAddress"
                      autocomplete="off"
                      style="width: 375%"></el-input>
          </el-form-item>
          <br />
          <el-tag>机构部门列表 ⮛⮛⮛⮛</el-tag>
          <br />
          <el-table ref="singleTable"
                    :data="mechanismTableData"
                    highlight-current-row>
            <el-table-column type="index"
                             width="50"> </el-table-column>

            <el-table-column prop="idOrder"
                             label="序号"> </el-table-column>
            <el-table-column property="mechanismDepartmentNumber"
                             label="机构部门编号">
            </el-table-column>
            <el-table-column property="mechanismDepartment"
                             label="机构部门">
            </el-table-column>
            <el-table-column property="sponsorFinancingManager"
                             label="主办融资经理">
            </el-table-column>
            <el-table-column property="coFinancingManager"
                             label="协办融资经理">
            </el-table-column>
            <el-table-column property="remark"
                             label="备注"> </el-table-column>
            <br />
            <br />
            <el-table-column prop="icon"
                             label="操作">
              <template slot-scope="scope">
                <template>
                  <el-popconfirm title="确定删除吗？"
                                 @confirm="delHandleDepartment(scope.row.id)">
                    <el-button type="text"
                               slot="reference">删除</el-button>
                  </el-popconfirm>
                </template>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination @size-change="handleSizeChange"
                         @current-change="handleCurrentChange"
                         layout="total, sizes, prev, pager, next, jumper"
                         :page-sizes="[10, 20, 50, 100]"
                         :current-page="current"
                         :page-size="size"
                         :total="total">
          </el-pagination>
          <br />
          <div class="button_style">
            <el-form-item>
              <el-button v-if="showAddDepartmentButton"
                         type="primary"
                         @click="addMechanismDepartment()">新增机构部门</el-button>
            </el-form-item>
            <br />
            <el-form-item>
              <el-button type="primary"
                         @click="submitForm('editForm')">保存机构信息</el-button>
            </el-form-item>
          </div>
        </el-form>
      </div>
    </el-dialog>
    <!-- 2  -->
    <el-dialog title=""
               :close-on-click-modal="false"
               append-to-body
               :visible.sync="addDepartmentVisible"
               width="30%">
      <el-form ref="DepartmentForm"
               :rules="DepartmentFormRules"
               :model="DepartmentForm"
               label-width="140px">
        <el-form-item label="机构编号">
          <el-input v-model="DepartmentForm.mechanismDepartmentNumber"
                    :disabled="true"></el-input>
        </el-form-item>
        <br />
        <el-form-item label="机构部门"
                      prop="mechanismDepartment">
          <el-select v-model="DepartmentForm.mechanismDepartment"
                     placeholder="机构部门"
                     style="width: 93%"
                     clearable="clearable">
            <!-- <el-option
            v-for="one in departmentList"
            :key="one"
            :value="one"
            :label="one"
          ></el-option> -->
            <el-option v-for="one in departmentList"
                       :key="one"
                       :value="one"
                       :label="one"></el-option>
          </el-select>
        </el-form-item>
        <br />
        <el-form-item label="主办融资经理"
                      prop="sponsorFinancingManager">
          <el-select v-model="DepartmentForm.sponsorFinancingManager"
                     placeholder="主办融资经理"
                     style="width: 93%"
                     clearable="clearable">
            <!-- <el-option
            v-for="one in departmentList"
            :key="one"
            :value="one"
            :label="one"
          ></el-option> -->
            <el-option v-for="one in HostManagerList"
                       :key="one"
                       :value="one"
                       :label="one"></el-option>
          </el-select>
        </el-form-item>

        <br />
        <el-form-item label="协办融资经理"
                      prop="coFinancingManager">
          <el-select v-model="DepartmentForm.coFinancingManager"
                     placeholder="协办融资经理"
                     style="width: 93%"
                     clearable="clearable">
            <!-- <el-option
            v-for="one in departmentList"
            :key="one"
            :value="one"
            :label="one"
          ></el-option> -->
            <el-option v-for="one in CoManagerList"
                       :key="one"
                       :value="one"
                       :label="one"></el-option>
          </el-select>
        </el-form-item>
        <br />
        <el-form-item label="备注">
          <el-input v-model="DepartmentForm.remark"></el-input>
        </el-form-item>
        <br />
        <el-form-item>
          <el-button type="primary"
                     @click="departmentOnSubmit('DepartmentForm')">立即保存</el-button>
          <el-button @click="addDepartmentVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!--详细信息对话框-->
    <el-dialog title="机构详细基本信息"
               :visible.sync="detailDialogVisible"
               width="80%"
               :before-close="DetailHandleClose">
      <el-descriptions :column="3"
                       border>
        <el-descriptions-item label="机构编号">{{
          mechanismDetailInfo.mechanismNumber
        }}</el-descriptions-item>
        <el-descriptions-item label="机构名称">{{
          mechanismDetailInfo.mechanismName
        }}</el-descriptions-item>
        <el-descriptions-item label="机构状态">{{
          mechanismDetailInfo.mechanismStatu
        }}</el-descriptions-item>
        <el-descriptions-item label="统一社会信用代码证">{{
          mechanismDetailInfo.usccl
        }}</el-descriptions-item>
        <el-descriptions-item label="证件有效期">{{
          mechanismDetailInfo.validity
        }}</el-descriptions-item>
        <el-descriptions-item label="法定代表人">{{
          mechanismDetailInfo.legalRepresentative
        }}</el-descriptions-item>
        <el-descriptions-item label="主办部门">{{
          mechanismDetailInfo.hostDepartment
        }}</el-descriptions-item>
        <el-descriptions-item label="拜访次数">{{
          mechanismDetailInfo.visit
        }}</el-descriptions-item>
        <el-descriptions-item label="来访次数">{{
          mechanismDetailInfo.visitedTime
        }}</el-descriptions-item>
        <el-descriptions-item label="创建日期">{{
          mechanismDetailInfo.created
        }}</el-descriptions-item>
        <el-descriptions-item label="注册地址">{{
          mechanismDetailInfo.registereAddress
        }}</el-descriptions-item>
        <el-descriptions-item label="营业地址">{{
          mechanismDetailInfo.businessAddress
        }}</el-descriptions-item>
      </el-descriptions>
      <br />
      <el-tag>机构部门列表 ⮛⮛⮛⮛</el-tag>
      <el-table ref="singleTable"
                :data="mechanismTableData"
                highlight-current-row>
        <el-table-column type="index"
                         width="50"> </el-table-column>

        <el-table-column prop="idOrder"
                         label="序号"> </el-table-column>
        <el-table-column property="mechanismDepartmentNumber"
                         label="机构部门编号">
        </el-table-column>
        <el-table-column property="mechanismDepartment"
                         label="机构部门">
        </el-table-column>
        <el-table-column property="sponsorFinancingManager"
                         label="主办融资经理">
        </el-table-column>
        <el-table-column property="coFinancingManager"
                         label="协办融资经理">
        </el-table-column>
        <el-table-column property="remark"
                         label="备注"> </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data: function () {
    return {
      //
      MechanismInfoVisible: false,

      detailDialogVisible: false,

      mechanismDetailInfo: [],

      pickerOptions: {},

      //新增的时候不能显示”新增机构部门“按钮 不合常理 需要现有机构才能有机构下面的部门.
      showAddDepartmentButton: false,

      // 暂存一下mechanism的id
      tempMechanismId: '',
      //暂存一下mechanismDepartmentNumber，在新增部门回填数据用
      tempMechanismDepartmentNumber: '',

      editFormRules: {
        mechanismType: [
          { required: true, message: '请选择机构类型', trigger: 'change' },
        ],
        mechanismName: {
          required: true,
          message: '请输入机构名称',
          trigger: 'blur',
        },
      },

      DepartmentFormRules: {
        mechanismDepartment: {
          required: true,
          message: '请输入机构部门',
          trigger: 'blur',
        },
        sponsorFinancingManager: {
          required: true,
          message: '请输入主板融资经理',
          trigger: 'blur',
        },
      },

      //分页参数的定义并设置默认参数
      total: 0,
      size: 10,
      current: 1,
      //角色表格记录的数据。数据会向后端发起请求获取。
      tableData: [],
      //创建searchForm{}对象，因为是弱语言，所以属性可以赋值时自动帮我们定义，比如searchForm.name赋值时就会自动帮我们添加name属性。
      searchForm: {},
      //"批量删除"按钮是否可禁用的标识。为了实现批量选择的数目为0时禁用"批量删除"的逻辑。
      delBtlStatu: true,
      //批量删除时被批量选择选中的记录的id的值，数组的形式。
      multipleSelection: [],
      loading: false, //loading标识符

      //第二个分页器的分页参数的定义并设置默认参数
      totalDepartment: 0,
      sizeDepartment: 10,
      currentDepartment: 1,

      HostManagerList: ['王国庆', 'liyili'],
      CoManagerList: ['Maji', 'Sahla'],
      departmentList: ['研发部', '测试部'],
      addDepartmentVisible: false,
      DepartmentForm: {},
      mechanismTableData: [],
      visible: false,
      //编辑和新增表单的数据。数据会向后端发起请求获取。
      editForm: { mechanismType: [] },
    };
  },

  created () {
    this.getMechanismList();
  },
  methods: {
    //elment ui文档提供的分页组件"每页页数"改变触发的回调函数，绑定在<el-pagination>的@size-change="handleSizeChange"属性中
    handleSizeChange (val) {
      console.log(`每页 ${val} 条`);
      this.size = val;
      this.getMechanismList(); //重新从后端获取新的Page对象实现每页显示多少条记录的逻辑
    },
    //elment ui文档提供的分页组件"当前页"改变触发的回调函数，绑定在<el-pagination>的@current-change="handleCurrentChange"属性中
    handleCurrentChange (val) {
      console.log(`当前页: ${val}`);
      this.current = val;
      this.getMechanismList(); //重新从后端获取新的Page对象实现当前第几页的逻辑
    },
    addHandle: function () {
      this.MechanismInfoVisible = true;
    },
    //elment ui文档提供的全选/全不选触发的回调函数
    toggleSelection (rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    //elment ui文档提供的勾选触发的回调函数，绑定在<el-table>的@selection-change="handleSelectionChange"属性中
    //其中val值是勾选对象的Array形式，val中的item.id就是行数据的id
    handleSelectionChange (val) {
      console.log('勾选');
      console.log(val);
      this.multipleSelection = val; //通过此处来确定表格中被批量勾选的所有记录对象的数组

      //先=赋值，再==比较，得到布尔类型结果。含义是没有勾选的会通过delBtlStatu=0也就是false来禁用"批量删除"按钮
      this.delBtlStatu = val.length == 0;
    },
    //elment ui文档提供的Form表单重设回调函数。供表单中"重置"按钮或其他方法调用
    resetForm (formName) {
      this.$nextTick(() => {
        this.$refs[formName].resetFields();
      });
      this.dialogVisible = false;
      this.editForm = { mechanismType: [] };
    },
    infoHandler (id) {
      this.$axios.get('/mechanism/info/' + id).then((res) => {
        this.detailDialogVisible = true;
        this.mechanismDetailInfo = res.data.data;
        this.getMchanismDepartmentTableDataList(id);
      });
    },
    getMechanismList () {
      this.loading = true;
      this.$axios
        .get('/mechanism/mechanismList', {
          //axios的get请求可以通过 params 对象传递参数。相当于："http://localhost:8080/sys/roles/list?name="普通用户"&current=1&size=10"
          //通过params传递name、current、size参数给后台。后台会根据参数名称接收这三个参数，然后通过Page的构造方法生成分页对象Page。
          params: {
            mechanismName: this.searchForm.mechanismName,
            current: this.current,
            size: this.size,
          },
        })
        .then((res) => {
          /*因为后端传来的是Page对象，所以"records"属性并不是我们定义的，是Page对象中的属性，诸如"current"、"size"、"total"等也是
           *"records"属性存放查询的记录。
           *下面操作获取查询到的记录数据、分页数据
           */
          this.tableData = res.data.data.records;
          this.size = res.data.data.size;
          this.current = res.data.data.current;
          this.total = res.data.data.total;
          this.loading = false;
        });
    },
    //编辑对话框回填用的回调函数
    editHandle (id) {
      this.$axios.get('/mechanism/info/' + id).then((res) => {
        this.editForm = res.data.data;
        this.MechanismInfoVisible = true;
        //显示 "新增部门机构按钮"
        this.showAddDepartmentButton = true;
        this.tempMechanismId = res.data.data.id;
        this.tempMechanismDepartmentNumber = res.data.data.mechanismNumber;
        this.getMchanismDepartmentTableDataList(id);
      });
    },
    //删除、批量删除用的回调函数
    delHandle (id) {
      var ids = [];

      if (id) {
        ids.push(id); //单个删除的情况，传入具体id
      } else {
        this.multipleSelection.forEach((row) => {
          ids.push(row.id); //传入null是批量删除的情况
        });
      }

      console.log(ids);

      this.$axios.post('/mechanism/delete', ids).then((res) => {
        var resData = res.data.data;
        this.$message({
          showClose: true,
          message: resData,
          type: 'success',
        });
        this.getMechanismList();
      });
    },

    getMchanismDepartmentTableDataList (id) {
      //id是mechanism的id，在mechanism_department关联表中用的
      this.loading = true;
      this.$axios
        .get('/department/departmentList', {
          //axios的get请求可以通过 params 对象传递参数。相当于："http://localhost:8080/sys/roles/list?name="普通用户"&current=1&size=10"
          //通过params传递name、current、size参数给后台。后台会根据参数名称接收这三个参数，然后通过Page的构造方法生成分页对象Page。
          params: {
            id: id,
            current: this.currentDepartment,
            size: this.sizeDepartment,
          },
        })
        .then((res) => {
          /*因为后端传来的是Page对象，所以"records"属性并不是我们定义的，是Page对象中的属性，诸如"current"、"size"、"total"等也是
           *"records"属性存放查询的记录。
           *下面操作获取查询到的记录数据、分页数据
           */
          this.mechanismTableData = res.data.data.records;
          console.log(
            '******************************' + this.mechanismTableData
          );
          this.sizeDepartment = res.data.data.size;
          this.currentDepartment = res.data.data.current;
          this.totalDepartment = res.data.data.total;
          this.loading = false;
        });
    },
    //新增机构部门时需要获取机构编号并进行回填处理
    addMechanismDepartment () {
      this.addDepartmentVisible = true;
      this.DepartmentForm.mechanismDepartmentNumber =
        this.tempMechanismDepartmentNumber;
    },
    handleCloseForDepartment () {
      this.MechanismInfoVisible = false;
      this.showAddDepartmentButton = false;
      this.resetForm();
      this.mechanismTableData = [];
    },
    handleClose () {
      this.visible = false;
    },
    DetailHandleClose () {
      this.detailDialogVisible = false;
    },
    //新增、编辑用的回调函数
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$axios
            .post(
              '/mechanism/' + (this.editForm.id ? 'update' : 'add'),
              this.editForm
            )
            .then((res) => {
              this.$message({
                showClose: true,
                message: '恭喜你，操作成功',
                type: 'success',
              });
              this.resetForm(formName);
              this.MechanismInfoVisible = false;
              this.getMechanismList();
            });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    departmentOnSubmit (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$axios
            .post(
              '/department/' + (this.DepartmentForm.id ? 'update' : 'add'),
              this.DepartmentForm
            )
            .then((res) => {
              this.$message({
                showClose: true,
                message: '恭喜你，操作成功',
                type: 'success',
              });
              this.resetForm(formName);
              //保证每次都有机构编号的回填  不这样的话新增保存成功之后就不会回填了
              // this.DepartmentForm.mechanismDepartmentNumber =
              this.addDepartmentVisible = false;
              this.getMchanismDepartmentTableDataList(this.tempMechanismId);
            });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },

    //删除、批量删除用的回调函数
    delHandleDepartment (id) {
      var ids = [];

      if (id) {
        ids.push(id); //单个删除的情况，传入具体id
      } else {
        this.multipleSelection.forEach((row) => {
          ids.push(row.id); //传入null是批量删除的情况
        });
      }

      console.log(ids);

      this.$axios.post('/department/delete', ids).then((res) => {
        var resData = res.data.data;
        this.$message({
          showClose: true,
          message: resData,
          type: 'success',
        });
        this.getMchanismDepartmentTableDataList(this.tempMechanismId);
      });
    },
  },
};
</script>

<style>
.el-dialog__body {
  /* border-top: 1px solid #dcdfe6; */
  /* border-bottom: 1px solid #dcdfe6; */
  max-height: 75% !important;
  overflow-y: auto;
}
.el-form-item {
  display: inline-block !important;
}

.button_style {
  position: relative;
  float: left;
  left: 30%;
}
.el-pagination {
  float: right;
  margin-top: 22px;
}
</style>
